<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/**
 * Handles data stored in JSON files.
 * 
 * Examples of use:
 * 
 * \code
 * // load
 * $Config->load(CONFIG.'json'.DS.'website.json');
 * $Config->load(CONFIG.'json'.DS.'plugin.json');
 * 
 * // read
 * $plugin_license = $Config->plugin['license'];
 * 
 * // write
 * $Config->website['name'] = 'My Project';
 * $Config->save(CONFIG.'json'.DS.'website.json', 'website');
 * \endcode
 */
class ConfigComponent
{
	/**
	 * Loads default configuration on startup.
	 * 
	 * @param $Controller Object
	 */
	function startup(Controller $Controller)
	{
		if (Core::config_autoload)
		{
			# website
			$this->load(APP.'config'.DS.'config.json');
			
			# plugin
			if (Core::$plugin !== false
				and file_exists(APP.'config'.DS.'plugins'.DS.Core::$plugin.'.json'))
			{
				$this->load(APP.'config'.DS.'plugins'.DS.Core::$plugin.'.json');
			}
		}
	}
	
	/**
	 * Adds data to configuration or loads a configuration file.
	 * 
	 * @param $data Mixed Array of data or filename.
	 */
	function load($data)
	{
		if (!is_array($data)) {
			$data = json_decode(file_get_contents($data));
		}
		foreach($data as $k => $v) {
			$this->$k = $v;
		}
	}
	
	/**
	 * Appends some configuration from data or a configuration file.
	 *  
	 * @param $data Mixed Array of data or filename.
	 */
	function append($data)
	{
		if (!is_array($data)) {
			$data = json_decode(file_get_contents($data));
		}
		foreach($data as $k => $v)
		{
			foreach($v as $kk => $vv) {
				$this->{$k}[$kk] = $vv;
			}
		}
	}
	
	/**
	 * Saves current configuration into a file.
	 *  
	 * @param $file Mixed  Array of data or filename.
	 * @param $what String Limit to main configuration.
	 */
	function save($file, $what=null)
	{
		# what?
		if (!empty($what) and !is_array($what)) {
			$what = explode(',', $what);
		}
		if (empty($what))
		{
			$what = array();
			foreach($this as $k => $v) {
				$what[] = $k;
			}
		}
		
		# get data
		$data = array();
		foreach($what as $k) {
			$data[$k] = $this->$k;
		}
		
		# save
		file_put_contents($file, json_encode($data));
#		chmod($file, 0664);
	}
}
?>